package com.cn.jdia.ets.data;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;

@Controller
public class AirlineData {

	@RequestMapping("/airline")
	public String getQuota(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String isInt = request.getParameter("isInt");
		System.out.println(isInt);

		@SuppressWarnings("resource")
		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("springmvc.xml");
		DataSource ds = (DataSource) w_context.getBean("dataSource2");

		List<Map<String, Object>> outList = new ArrayList<>();
		List<Map<String, Object>> inList = new ArrayList<>();

		try {
			Connection conn = ds.getConnection();
			Statement st = conn.createStatement();

			String outStr = "";
			String inStr = "";
			if (isInt==null) {
				outStr = "select AIRPORT_CITY,FLIGHT_NUM from TAOOUT";
				inStr = "select AIRPORT_CITY,FLIGHT_NUM from TAOIN";
			
			} else {
				outStr = "select AIRPORT_CITY,FLIGHT_NUM from TAOOUT_INT";
				inStr = "select AIRPORT_CITY,FLIGHT_NUM from TAOIN_INT";
			}

			ResultSet rs1 = st.executeQuery(outStr);
			while (rs1.next()) {
				Map<String, Object> outMap = new HashMap<>();
				outMap.put("name", rs1.getString("AIRPORT_CITY"));
				outMap.put("value", rs1.getInt("FLIGHT_NUM") * 5);
				outList.add(outMap);
			}
			rs1.close();

			ResultSet rs2 = st.executeQuery(inStr);
			while (rs2.next()) {
				Map<String, Object> inMap = new HashMap<>();
				inMap.put("name", rs2.getString("AIRPORT_CITY"));
				inMap.put("value", rs2.getInt("FLIGHT_NUM") * 5);
				inList.add(inMap);
			}
			rs2.close();

			st.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, List<Map<String, Object>>> fMap = new HashMap<>();
		fMap.put("outList", outList);
		fMap.put("inList", inList);

		Gson gson = new Gson();
		String json = gson.toJson(fMap);
		// System.out.println(json);

		out.print(json);
		out.flush();
		out.close();

		return null;
	}
}
